package io.rocketman.common.plugin;

import io.rocketman.common.plugin.factory.PluginFactory;
import org.reflections.Reflections;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author He Peng
 * @create 2018-05-27 12:09
 * @update 2018-05-27 12:09
 * @updatedesc : 更新说明
 * @see
 */
public class PluginLoader<T> {

    private static final Map<Class<?> , PluginLoader<?>> PLUGIN_LOADER_INSTANCES = new ConcurrentHashMap<>();
    private static final Map<Class<?> , Map<String , Object>> PLUGIN_INSTANCES = new ConcurrentHashMap<>();
    private static final PluginFactory PLUGIN_FACTORY = (PluginFactory) PluginLoader.getPluginLoader(PluginFactory.class).getRuntimePlugin();

    private Class<T> pluginInterfaceClass;
    private String defaultPluginName;
    private Class<? extends T> runtimePluginClass;
    private T runtimePluginInstance;
    private Map<String , Class<? extends T>> pluginClasses = new ConcurrentHashMap<>();
    private Map<String, T> pluginInstances = new ConcurrentHashMap<>();
    private Map<Class<T> , Reflections> reflections = new ConcurrentHashMap<>();

    private PluginLoader(Class<T> pluginInterfaceClass) {
        this.pluginInterfaceClass = pluginInterfaceClass;
        this.defaultPluginName = pluginInterfaceClass.getAnnotation(PluginInterface.class).value();
        loadPlugins(pluginInterfaceClass);
    }

    public static <T> PluginLoader getPluginLoader(Class<T> pluginInterfaceClass) {
        checkPluginInterfaceType(pluginInterfaceClass);
        PluginLoader<T> pluginLoader = (PluginLoader<T>) PLUGIN_LOADER_INSTANCES.get(pluginInterfaceClass);
        if (pluginLoader == null) {
            pluginLoader = newPluginLoader(pluginInterfaceClass);
            PLUGIN_LOADER_INSTANCES.put(pluginInterfaceClass , pluginLoader);
        }
        return pluginLoader;
    }

    private static <T> PluginLoader<T> newPluginLoader(Class<T> pluginInterfaceClass) {
        PluginLoader<T> pl = new PluginLoader<>(pluginInterfaceClass);
        return pl;
    }


    public T getRuntimePlugin() {
        if (this.runtimePluginInstance == null) {
            try {
                if (this.runtimePluginClass != null) {
                    this.runtimePluginInstance = this.runtimePluginClass.newInstance();
                } else {
                    this.runtimePluginClass = createDynamicPluginClass(pluginInterfaceClass);
                    this.runtimePluginInstance = this.runtimePluginClass.newInstance();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return this.runtimePluginInstance;
    }


    public T getPlugin(String name) {
        T plugin = this.pluginInstances.get(name);
        if (plugin == null) {
            Class<? extends T> pluginClass = this.pluginClasses.get(name);
            try {
                plugin = pluginClass.newInstance();
                this.pluginInstances.put(name , plugin);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return plugin;
    }

    private synchronized void loadPlugins(Class<T> pluginInterfaceClass) {
        if (this.pluginClasses != null) {
            return;
        }
        Reflections rflt = this.reflections.get(pluginInterfaceClass);
        if (rflt == null) {
            rflt = new Reflections(pluginInterfaceClass.getPackage().getName());
            this.reflections.put(pluginInterfaceClass , rflt);
        }
        Set<Class<? extends T>> plugins0 = rflt.getSubTypesOf(pluginInterfaceClass);
        // TODO 从 PluginFactory 中获取 , 合并处理
        Map<String, Class<? extends T>> plugins1 = PLUGIN_FACTORY.getPlugins(pluginInterfaceClass);

        Set<Class<? extends T>> mergedPlugins = new HashSet<>(8);
        if (plugins0 != null) {
            mergedPlugins.addAll(plugins0);
        }

        if (plugins1 != null) {
            mergedPlugins.addAll((Collection<? extends Class<? extends T>>) plugins1);
        }

        if (mergedPlugins == null || mergedPlugins.isEmpty()) {
            return;
        }

        for (Class<? extends T> subTypeClass : mergedPlugins) {
            boolean isPlugin = isPlugin(subTypeClass);
            if (! isPlugin) {
                continue;
            }
            Plugin pluginAnnotation = subTypeClass.getAnnotation(Plugin.class);
            String pluginName = pluginAnnotation.value();
            this.pluginClasses.put(pluginName , subTypeClass);
            if (pluginName.equalsIgnoreCase(this.defaultPluginName)) {
                this.runtimePluginClass = subTypeClass;
            }

            if (subTypeClass.getAnnotation(RuntimePlugin.class) != null) {
                this.runtimePluginClass = subTypeClass;
            }
        }
    }

    private Class<? extends T> createDynamicPluginClass(Class<T> pluginInterfaceClass) {
        String code = generateDynamicPluginCode(pluginInterfaceClass);
        // TODO 先忽略该功能 ， 实现核心功能
        return null;
    }

    private String generateDynamicPluginCode(Class<T> pluginInterfaceClass) {
        // TODO
        return null;
    }

    private boolean isPlugin(Class<? extends T> subTypeClass) {
        Class<?>[] interfaceArray = subTypeClass.getInterfaces();
        if (interfaceArray == null) {
//            throw new IllegalArgumentException(subTypeClass + " no interface is implemented");
            return false;
        }
        List<Class<?>> interfaces = Arrays.asList(subTypeClass.getInterfaces());
        if (! interfaces.contains(this.pluginInterfaceClass)) {
//            throw new IllegalArgumentException(subTypeClass + " no implementation of the " + this.pluginInterfaceClass + " interface");
            return false;
        }
        Plugin pluginAnnotation = subTypeClass.getAnnotation(Plugin.class);
        if (pluginAnnotation == null) {
//            throw new IllegalArgumentException("not a plugin cause not found @Plugin annotation at " + subTypeClass);
            return false;
        }
        return true;
    }

    private static <T> void checkPluginInterfaceType(Class<T> cls) {
        if (! cls.isInterface()) {
            throw new IllegalArgumentException(cls + " is not interface type");
        }
        if (cls.getAnnotation(PluginInterface.class) == null) {
            throw new IllegalArgumentException("not found @PluginInterface annotation at " + cls);
        }
    }


    public boolean hasPlugin( String name) {
        return this.pluginClasses.containsKey(name);
    }
}
